<template>
  <div>
    <!-- <div class="app-container">
      <div class="search-container">
        安全设置
     // </div>
   // </div> -->
    <el-row :gutter="18">
      <el-col :span="8">
        <el-card style="max-width: 300px;height: 300px;margin: 20px 20px;">
          <table>
            <tr>
              <td>
                <div>
                  <img src="https://img2.baidu.com/it/u=3270548921,432114510&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                    alt="Image" style="width: 120px;height: 120px;margin: 15px 50px;" />
                </div>
              </td>
            </tr>
            <tr>
              <td style="text-align: center;">
                登录密码
              </td>
            </tr>
            <tr>
              <td style="text-align: center;color: greenyellow;">
                已设置
              </td>
            </tr>
            <tr>
              <td>
                <el-button type="primary" style="text-align: center;margin: 10px 80px;"
                  @click="dialogVisible = true">修改</el-button>
              </td>
            </tr>
          </table>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card style="max-width: 300px;height: 300px;margin: 20px 20px;">
          <table>
            <tr>
              <td>
                <div>
                  <img src="https://bpic.51yuansu.com/pic3/cover/02/02/36/599d672c008b1_610.jpg" alt="Image"
                    style="width: 120px;height: 120px;margin: 15px 70px;" />
                </div>
              </td>
            </tr>
            <tr>
              <td style="text-align: center;">
                修改手机号
              </td>
            </tr>
            <tr>
              <td style="text-align: center;color: greenyellow;">
                已绑定
              </td>
            </tr>
            <tr>
              <td>
                <el-button type="primary" style="text-align: center;margin: 10px 80px;"
                  @click="updatephone()">修改手机号</el-button>
              </td>
            </tr>
          </table>
        </el-card>

      </el-col>
    </el-row>
    <el-row :gutter="18">
      <el-col :span="8">
        <el-card style="max-width: 300px;height: 300px;margin: 20px 20px;">
          <table>
            <tr>
              <td>
                <div>
                  <img src="https://bpic.51yuansu.com/pic2/cover/00/45/32/5814def5593a1_610.jpg" alt="Image"
                    style="width: 120px;height: 120px;margin: 20px 70px;" />
                </div>
              </td>
            </tr>
            <tr>
              <td style="text-align: center;color:brown;">
                账号注销
              </td>
            </tr>
            <tr>
              <td style="text-align: center;">
                彻底关闭不再使用平台账号
              </td>
            </tr>
            <tr>
              <td>
                <el-button style="text-align: center;margin: 10px 80px;" @click="deleteAccounts()">注销账户</el-button>
              </td>
            </tr>
          </table>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card style="max-width: 300px;height: 300px;margin: 20px 20px;">
          <table>
            <tr>
              <td>
                <div>
                  <img src="https://img95.699pic.com/xsj/30/o9/y8.jpg%21/fh/300" alt="Image"
                    style="width: 120px;height: 120px;margin: 20px 70px;" />
                </div>
              </td>
            </tr>
            <tr>
              <td style="text-align: center;color:blue;">
                安全密码
              </td>
            </tr>
            <tr>
              <td style="text-align: center;">
                审批、支付密码设置
              </td>
            </tr>
            <tr>
              <td>
                <el-button style="text-align: center;margin: 10px 80px;">立即设置</el-button>
              </td>
            </tr>
          </table>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 修改密码 -->
  <div>
    <el-dialog v-model="dialogVisible" title="修改密码" width="500">
      <span>
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
          class="demo-ruleForm" status-icon destroy-on-close>
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input v-model="ruleForm.oldPassword" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="ruleForm.newPassword" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="newPasswordTwo">
            <el-input v-model="newpwd2.newPasswordTwo" show-password />
          </el-form-item>
        </el-form>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </span>
    </el-dialog>
  </div>

  <!-- 修改手机号 -->
  <div>
    <el-dialog v-model="dialogVisibles" title="验证手机号码" width="500">
      <span>
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="phoneform" :rules="rules" label-width="auto"
          class="demo-ruleForm" status-icon destroy-on-close>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="phoneform.phone" :disabled="true" />
          </el-form-item>
          <el-form-item label="验证码" prop="VerificationCode">
            <el-input v-model="phoneform.VerificationCode">
              <template #suffix>
                <div v-if="messageCodeVis" class="second-text">{{ countdown }}秒后重新获取</div>
                <el-button v-else type="primary" link @click="sendCode()">获取验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-form-item>
          <el-button type="primary" @click="enddata()">
            下一步
          </el-button>
        </el-form-item>
      </span>
    </el-dialog>

    <!-- 新修改手机号 -->
    <el-dialog v-model="dialogVisibled" title="修改手机号码" width="500">
      <span>
        <el-form :model="form2" label-width="120px">
          <el-form-item label="手机号码：">
            <el-input v-model="form2.personage_Phone" />
          </el-form-item>
          <el-form-item label="验证码：">
            <el-input v-model="code2">
              <template #suffix>
                <div v-if="messageCodeVis2" class="second-text">{{ countdown2 }}秒后重新获取</div>
                <el-button v-else type="primary" link @click="sendCode2()">获取验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="enddata2()">确认</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios';
import personalAPI from '@/api/PersonalSettings/index'
import { personalData } from '@/api/PersonalSettings/model'

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const dialogVisible = ref(false)
const ruleForm = reactive<personalData>({
  newPassword: "",
  oldPassword: "",
})
const newpwd2 = reactive({
  newPasswordTwo: "",
})

//校验
const rules = reactive<FormRules<RuleForm>>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在6-10个字符', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 10, message: '长度在6-10个字符', trigger: 'blur' },
  ],
})
//修改密码
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //判断密码不能相同
      if (ruleForm.oldPassword == ruleForm.newPassword) {
        ElMessage({
          message: '新密码与旧密码不能相同',
          type: 'error'
        })
        return
      }
      if (newpwd2.newPasswordTwo != ruleForm.newPassword) {
        ElMessage({
          message: '确认密码与新密码不一致',
          type: 'error'
        })
        return
      }
      personalAPI.changePassword(ruleForm).then((res: any) => {
        if (res.data == -1) {
          ElMessage
            ({
              message: '旧密码错误',
              type: 'error'
            })
        }
        if (res.data == 1) {
          ElMessage({
            message: '修改成功',
            type: 'success'
          })
        }
        else {
          ElMessage({
            message: '修改失败',
            type: 'error'
          })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// const phoneform = reactive({
//   phone: localStorage.getItem('phone')?.substring(0, 3) + '******' + localStorage.getItem('phone')?.substring(9, 11),
//   //验证码
//   VerificationCode: ""
// })

//旧修改手机号
const phoneform = reactive({
  phone: '',
  VerificationCode: ''
})
//反填手机号
const dialogVisibles = ref(false)
const updatephone = () => {
  dialogVisibles.value = true
  //手机号和id
  let userid = localStorage.getItem("userid")
  let phone = localStorage.getItem("phone")
  phoneform.phone = phone.substring(0, 3) + "******" + phone.substring(9, 11)
  sessionStorage.setItem("Phone", phone)
  sessionStorage.setItem("Userid", userid)
}


//发送验证码
const messageCodeVis = ref(false)
let countdown = ref(0)
const sendCode = () => {
  countdown.value = 60
  messageCodeVis.value = true
  startCountdown()//倒计时

  let phones = sessionStorage.getItem("Phone")
  // console.log(phones)


  personalAPI.SendPhoneCode(phones).then(res => {
    let ccods = res.data
    localStorage.setItem("Code", ccods)
    //console.log(ccods)
  })
  // const reg = /^1[3456789]\d{9}$/;
  // if(!form.value.phone) return ElMessage.error('请输入手机号码')
  // if (!reg.test(form.value.phone)) return
}


/* 倒计时 */
const startCountdown = () => {
  const intervalId = setInterval(() => {
    debugger;
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(intervalId)
      messageCodeVis.value = false
    }
  }, 1000)
}
// const rulesForm = {
//   phone: [
//   { required: true, message: '请输入手机号码', trigger: 'blur' },
//   { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
//   ]
// }
//下一步
const enddata = () => {
  let cods = localStorage.getItem("Code")
  if (phoneform.VerificationCode == cods) {
    //验证码正确，跳转修改手机号页面 
    dialogVisibles.value = false
    dialogVisibled.value = true
  }
  else {
    ElMessage.error("验证码错误")
    return;
  }

}


//新修改手机号
const dialogVisibled = ref(false)
const form2 = ref({
  id: "",
  personage_Phone: ''
})

const code2 = ref('')
const messageCodeVis2 = ref(false)
let countdown2 = ref(0)
const sendCode2 = () => {
  countdown2.value = 60;
  messageCodeVis2.value = true;
  startCountdown2(); // 启动倒计时
  SendPhoneCode(form2.value.personage_Phone).then(res => {
    let ccods2 = res;
    localStorage.setItem("Code2", ccods2);
  }).catch(err => {
    // 处理发送验证码失败的情况
    messageCodeVis2.value = false; // 发送失败时需要手动设置为false
    clearInterval(intervalId2); // 清除定时器
    countdown2.value = 0; // 重置倒计时时间
    ElMessage.error("发送验证码失败，请重试");
  });
}
/* 倒计时 */
const startCountdown2 = () => {
  let intervalId2 = setInterval(() => {
    if (countdown2.value > 0) {
      countdown2.value--;
    } else {
      clearInterval(intervalId2);
      messageCodeVis2.value = false; // 倒计时结束后隐藏倒计时信息
    }
  }, 1000);
}
const enddata2 = () => {
  // 验证手机号和验证码等逻辑
  if (form2.value.personage_Phone === "") {
    ElMessage.error("请输入手机号");
    return;
  }

  let reg = /^1[0-9]{10}$/
  if (form2.value.personage_Phone == "") {
    ElMessage.error("请输入手机号")
    return;
  }
  if (!reg.test(form2.value.personage_Phone)) {
    ElMessage.error('请输入正确手机号!');
    return;
  }
  //判断验证码不能为空
  debugger;
  if (code2.value == "") {
    ElMessage.error("请输入验证码");
    return;
  }
  let cods2 = localStorage.getItem("Code2");
  if (code2.value !== cods2) {
    ElMessage.error("验证码错误");
    return;
  }

  form2.value.id = sessionStorage.getItem("Userid")
  //修改手机号
  updatePhone(form2.value).then(res => {
    dialogVisibled.value = false
    ElMessage.success("修改手机号成功")
  })

}
</script>